package com.vernon.demo.utils;

/**
 * @Auther: vernon
 * @Date: 2021/4/26 23:04
 * @Description:
 */


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

public class PmUtil {

    public static Logger logger = LoggerFactory.getLogger(PmUtil.class);
    private static final String PRADAR = "com.pamirs.pradar.Pradar";

    private static Class<?> ClAZZ = null;
    private static Method isClusterTestMethod = null;
    private static Method setClusterTestMethod = null;

    static {
        ClassLoader classLoader = PmUtil.class.getClassLoader();
        try {
            ClAZZ = classLoader.loadClass(PRADAR);

            isClusterTestMethod = ClAZZ.getDeclaredMethod("isClusterTest");
            if (!isClusterTestMethod.isAccessible()) {
                isClusterTestMethod.setAccessible(true);
            }


            setClusterTestMethod = ClAZZ.getDeclaredMethod("setClusterTest",
                    boolean.class);
            if (!setClusterTestMethod.isAccessible()) {
                setClusterTestMethod.setAccessible(true);
            }

        } catch (Throwable t) {
            logger.error("加载Pradar类异常,{}", t.getMessage());
        }
    }

    public static boolean pradarInited() {
        return ClAZZ != null;
    }


    /**
     * 给业务代码 或者其他中间件使用  判断当前线程是不是测试线程的方法
     * 压测流量:true
     * 业务流量:false
     */
    public static boolean isPressureMeasurement() {
        try {
            return (Boolean) isClusterTestMethod.invoke(null);
        } catch (Exception e) {
            try {
                return (Boolean) Class.forName(PRADAR)
                        .getDeclaredMethod("isClusterTest")
                        .invoke(null);
            } catch (Exception t) {
                logger.warn("识别压测流量失败！");
            }
        }
        return false;
    }

    /**
     * 业务线程转换成压测线程
     */
    public static void turnCurrentThreadIntoPressureMeasurement() {
        try {
            setClusterTestMethod.invoke(null, Boolean.TRUE);
        } catch (Exception e) {
            try {
                Class.forName(PRADAR)
                        .getDeclaredMethod("setClusterTest", boolean.class)
                        .invoke(null, Boolean.TRUE);
            } catch (Exception t) {
                logger.warn("业务线程转换成压测线程异常！");
            }
        }

    }

    /**
     * 压测线程转换成业务线程
     */
    public static void backCurrentThreadIntoNormal() {
        try {

            setClusterTestMethod.invoke(null, Boolean.FALSE);
        } catch (Exception e) {
            try {
                Class.forName(PRADAR)
                        .getDeclaredMethod("setClusterTest", boolean.class)
                        .invoke(null, Boolean.FALSE);
            } catch (Exception t) {
                logger.warn("压测线程转换成业务线程异常！");
            }

        }
    }
}